<?php
namespace app\administrative\controller;

use app\common\model\Administrative;
use app\common\model\Contract;
use app\common\model\ContractEquipment;
use app\common\model\Customer;
use app\common\model\CustomerAdministrativeCenter;
use app\common\model\Engineers;
use app\common\model\WorkEquipment;
use app\common\model\WorkOrderRemarks;
use think\Cache;
use think\db;
use app\common\model\Equipments;


/**          YSF
 * Class Workorder
 * @package app\administrative\controller
 *       行政中心  工单管理
 */
class Workorder extends Base
{
    // 声明一个属性 用来装模型
    protected static $workModel;

    // 初始化方法  用来实例化模型
    public function __construct()
    {
        parent::__construct();
        // 实例化工单 模型
        self::$workModel = new \app\common\model\WorkOrder();
    }

    /*
     *  渲染 工单 列表页面
     */
    public function index($workorderstatus = '')
    {

        // 获取当前登录用户所属行政中心id
        $a_id = session($this->set['db_name'].'a_id');
        // 获取当前登录用户id
        $u_id = session($this->set['db_name'].'uid');
        // 获取当前登录用户名
        $username = session($this->set['db_name'].'username');

        // 实例化administrative_user表
        $administrativeUserModel = new Administrative();
        $wUser['id'] = $u_id;
        // 查询当前用户属于哪个角色分组
        $atData = $administrativeUserModel->getAdministrativeUser($wUser);
        // 查询登录用户所属哪个角色
        $wGroup['id'] = $atData['groupid'];
        $groupData = $administrativeUserModel->getAdministrativeGroup($wGroup);
        // 1 : 超管     所有
        // 2 : 前台     所有
        // 4 : 工程部   未指派给工程人员的
        // 5 : 工程人员 已指派给工程人员的

        // 表示超管登录，显示所有
        if ($groupData['id'] == 1) {
            // 初始化默认为未指派
            if ($workorderstatus == 3) {
                $where['a.work_order_status'] = ['between',[2,3]];
            }
            if ($workorderstatus == 4) {
                $where['a.work_order_status'] = ['>','4'];
            }
        }
        // 表示前台登录，显示所有
        if ($groupData['id'] == 2) {
            // 初始化默认为未指派
            if ($workorderstatus == 3) {
                $where['a.work_order_status'] = ['between',[2,3]];
            }
            if ($workorderstatus == 4) {
                $where['a.work_order_status'] = ['>','4'];
            }
        }
        // 表示工程部登录
        if ($groupData['id'] == 4){
            // 初始化默认为未指派
            if ($workorderstatus == 3) { // 显示所有未指派工程部工单
                $where['a.work_order_status'] = ['in','5,7'];
            }
            if ($workorderstatus == 4) { // 显示所有已指派工程部工单
                $where['a.work_order_status'] = ['in','7,8,9'];
            }
        }
        // 表示工程人员登录
        if ($groupData['id'] == 5){
            // 初始化默认为未指派
            if ($workorderstatus == 3) { // 显示所有已指派工程人员工单
                $where['a.work_order_status'] = ['in','8,9'];
            }
            if ($workorderstatus == 4) { // 显示所有已指派工程人员工单
                $where['a.work_order_status'] = ['in','8,9'];
            }
        }



        // 显示登录用户所属行政中心下面所有工单
        if (!empty($a_id)) {
            $where['a.administrative_id'] = $a_id;
        }

        // 接收ajax请求模糊查询数据
        $searchObj = request()->get();


        // 接收当前页码数
        $nowPage = input('get.page') ? input('get.page') : 1;
        // 设置每页显示条数
        $limits = config('pagesize');


        // 查询 的字段
        $field = 'a.order_number,a.audit_status,b.username,b.telphone,a.business_id,a.province,a.city,a.area,a.service_address,f.company_name a_name,
                  a.combo_money,a.order_time,c.for_core_time,c.renew_date,a.work_order_status,
                  e.engineers_name,a.remarks,a.order_time,a.work_order_id,b.user_id,c.contract_id';
        // 连表
        $join = [
            ['rq_customer b', 'b.user_id = a.user_id','LEFT'],                     // 客户表 对应 工单表
            ['rq_contract c', 'c.contract_id = a.contract_id','LEFT'],             // 合同表 对应 工单表
            ['rq_operation_info d', 'd.o_id = a.operation_id','LEFT'],             // 运营中心表 对应 工单表
            ['rq_engineers e', 'e.engineers_id = a.repair_id','LEFT'],             // 工程人员表 对应 工单表
            ['rq_administrative_info f', 'f.a_id = a.administrative_id','LEFT']    // 行政中心表 对应 工单表
        ];

        // 判断工单类型状态是否有值
        if (!empty($searchObj['status'])) {
            // 判断是否移机
            if ($searchObj['status'] == 5) {
                $where['a.business_id'] = ['in', '5,9,10'];
            } else {
                $where['a.business_id'] = $searchObj['status'];
            }
        }
        //判断用户有没有选择处理状态
        if (!empty($searchObj['workStatus'])) {
            if ($searchObj['workStatus'] == 13) {
                $where['a.work_order_status'] = ['in','9,10,11,12'];
            }else{
                $where['a.work_order_status'] = $searchObj['workStatus'];
            }
        }
        //判断用户有没有选择业务类型
        if (!empty($searchObj['type'])) {
            $where['a.business_id'] = $searchObj['type'];
        }
        // 判断用户有没有输入工单号
        if (!empty($searchObj['order_number'])) {
            $where['a.order_number'] = $searchObj['order_number'];
        }
        // 判断用户有没有输入用户名
        if (!empty($searchObj['username'])) {
            $where['b.username'] = $searchObj['username'];
        }
        // 判断用户有没有输入联系电话
        if (!empty($searchObj['telphone'])) {
            $where['b.telphone'] = $searchObj['telphone'];
        }
        // 判断用户有没有输入工程人员
        if (!empty($searchObj['engineers_name'])) {
            $where['e.engineers_name'] = $searchObj['engineers_name'];
        }
        // 判断用户有没有输入工程人员编号
        if (!empty($searchObj['engineers_number'])) {
            $where['e.engineers_number'] = $searchObj['engineers_number'];
        }
        // 判断用户有没有输开始日期 // 判断用户有没有输结束日期
        if (!empty($searchObj['startTime']) && !empty($searchObj['endTime'])) {
            $where['a.order_time'] = ['between', [strtotime($searchObj['startTime']), strtotime($searchObj['endTime']) + (60 * 60 * 24 - 1)]];//终止到当天23:59:59
        } else if (!empty($searchObj['startTime'])) {
            $where['a.order_time'] = ['>=', strtotime($searchObj['startTime'])];
        } else if (!empty($searchObj['endTime'])) {
            $where['a.order_time'] = ['<=', strtotime($searchObj['endTime']) + (60 * 60 * 24 - 1)];
        }
        // 更新时间
        $startUpdateTime = input('get.startUpdateTime') ? input('get.startUpdateTime') : '';
        $endUpdateTime = input('get.endUpdateTime') ? input('get.endUpdateTime') : '';
        if(!empty($startUpdateTime) && !empty($endUpdateTime)){
            $where['a.update_time'] = ['between time', [strtotime($startUpdateTime),strtotime($endUpdateTime)+(60*60*24)]];
        }

        // 查询未被逻辑删除的数据
        $where['a.is_delete'] = 0;
        // 主表
        $dbName = 'rq_work_order';

        //过滤审核通过的数据
//        $where['a.audit_status'] = ['<>',1];

        $order = [
            'a.audit_status'=>'desc',
            'a.work_order_status'=>'ASC',
            'a.update_time'=>'desc',
            'a.order_time'=>'desc'

        ];

        // 调用方法
        $data = self::$workModel->getAll($field, $where, $nowPage, $limits, $dbName, $join,$order);

        // 判断状态码是否为空
        $count = self::$workModel->getCount($where, $dbName, $join);

        // 获取工单类型
        $type = config('workorder_type');
        // 获取工单状态
        $status = config('work_order_status');
        $workType = ['1' => '续费', '2' => '换芯', '3' => '新装', '4' => '拆机', '5' => '移机',
            '6' => '维修', '7' => '续费+维修', '8' => '换芯+维修', '9' => '移机(拆)', '10' => '移机(装)',
        ];

        // 计算总的页面数
        $allPage = intval(ceil($count / $limits));
        $this->assign('nowPage', $nowPage); //当前页
        $this->assign('allPage', $allPage); //总页数
        $this->assign('count', $count);// 总的条数
        $this->assign('work_order_status', $status);// 工单状态

        // 判断数据是否有值
        if (!empty($data)) {
            // 类型 状态 转换
            foreach ($data as $k => $v) {
                $data[$k]['business_id'] = $workType[$v['business_id']];
                $data[$k]['work_order_status'] = $status[$v['work_order_status']];
                $data[$k]['order_status'] = $v['work_order_status'];
                if (strlen($v['for_core_time']) < 5) {
                    $data[$k]['for_core_time'] = '';
                }else{
                    $data[$k]['for_core_time'] = date('Y/m/d', $v['for_core_time']);
                }
                $data[$k]['renew_date'] = $v['renew_date'] ? $v['renew_date'] : '';
                $data[$k]['order_time'] = date('Y/m/d', $v['order_time']);
                $data[$k]['nowPage'] = $nowPage;
                $data[$k]['allPage'] = $allPage;
                $data[$k]['count'] = $count;
                $data[$k]['renewcore'] = $workorderstatus;     // 未指派还是已指派状态数
                $data[$k]['service_address'] = $v['province'].$v['city'].$v['area'].$v['service_address'];
            }
        }

        // 返回
        return $data;

    }

    /**
     * @return mixed|\think\response\Json
     *       渲染未指派工单页面
     */
    public function unassigned()
    {

        // 获取当前登录用户id
        $u_id = session($this->set['db_name'].'uid');

        // 实例化administrative_user表
        $administrativeUserModel = new Administrative();
        $wUser['id'] = $u_id;
        // 查询当前用户属于哪个角色分组
        $atData = $administrativeUserModel->getAdministrativeUser($wUser);
        // 查询登录用户所属哪个角色
        $wGroup['id'] = $atData['groupid'];
        $groupData = $administrativeUserModel->getAdministrativeGroup($wGroup);
        $groupDataId = $groupData['id'];
        // ---------------------------------------------------------------------

        $workorderstatus = 3;
        $data = $this->index($workorderstatus);

        // 获取工单类型
        $type = config('workorder_type');
        // 获取工单状态
        $status = config('work_order_status');
        $workType = ['1' => '续费', '2' => '换芯', '3' => '新装', '4' => '拆机', '5' => '移机',
            '6' => '维修', '7' => '续费+维修', '8' => '换芯+维修', '9' => '移机(拆)', '10' => '移机(装)',
        ];

        // 判断用户是否有值
        if (input('get.page')) {
            return json($data);
        }

        // 模板赋值 数据，类型
        $this->assign(
            [
                'data' => $data,
                'type' => $type,
                'workType' => $workType,
                'status' => $status,
                'workorderstatus' => $workorderstatus,
                'groupDataId' => $groupDataId
            ]);
        // 调用视图
        return $this->fetch('index');

    }

    /**
     * @return mixed|\think\response\Json
     *       渲染已指派工单页面
     */
    public function assigned()
    {

        // 获取当前登录用户id
        $u_id = session($this->set['db_name'].'uid');

        // 实例化administrative_user表
        $administrativeUserModel = new Administrative();
        $wUser['id'] = $u_id;
        // 查询当前用户属于哪个角色分组
        $atData = $administrativeUserModel->getAdministrativeUser($wUser);
        // 查询登录用户所属哪个角色
        $wGroup['id'] = $atData['groupid'];
        $groupData = $administrativeUserModel->getAdministrativeGroup($wGroup);
        $groupDataId = $groupData['id'];
        // ---------------------------------------------------------------------

        $workorderstatus = 4;
        $data = $this->index($workorderstatus);

        // 获取工单类型
        $type = config('workorder_type');
        // 获取工单状态
        $status = config('work_order_status');
        $workType = ['1' => '续费', '2' => '换芯', '3' => '新装', '4' => '拆机', '5' => '移机',
            '6' => '维修', '7' => '续费+维修', '8' => '换芯+维修', '9' => '移机(拆)', '10' => '移机(装)',
        ];

        // 判断用户是否有值
        if (input('get.page')) {
            return json($data);
        }

        // 模板赋值 数据，类型
        $this->assign(
            [
                'data' => $data,
                'type' => $type,
                'workType' => $workType,
                'status' => $status,
                'workorderstatus' => $workorderstatus,
                'groupDataId' => $groupDataId
            ]);
        // 调用视图
        return $this->fetch('index');

    }

    /**
     * @param $businessid
     * @return false|\PDOStatement|string|\think\Collection
     *       处理  (续费 || 换芯)数据  控制器
     */
    public function renewcore($businessid)
    {

        // 获取当前登录用户所属行政中心id
        $a_id = session($this->set['db_name'].'a_id');
        // 获取当前登录用户id
        $u_id = session($this->set['db_name'].'uid');

        // 实例化administrative_user表
        $administrativeUserModel = new Administrative();
        $wUser['id'] = $u_id;
        // 查询当前用户属于哪个角色分组
        $atData = $administrativeUserModel->getAdministrativeUser($wUser);
        // 查询登录用户所属哪个角色
        $wGroup['id'] = $atData['groupid'];
        $groupData = $administrativeUserModel->getAdministrativeGroup($wGroup);

        // 表示工程部登录
        if ($groupData['id'] == 4){
           // 显示所有已指派工程部工单//所有已指派工程人员工单
           $where['a.work_order_status'] = ['in','5,6,7,8,9'];
        }
        // 表示工程人员登录
        if ($groupData['id'] == 5){
            // 所有工程人员工单
            $where['a.work_order_status'] = ['in','8,9'];
        }

        // 显示登录用户所属行政中心的工单
        if (!empty($a_id)) {
            $where['a.administrative_id'] = $a_id;
        }

        // 接收ajax请求模糊查询数据
        $searchObj = request()->get();

        // 接收 续费 或 换芯 对应值
        if (!empty($businessid)) {
            $where['a.business_id'] = $businessid;
        }

        // 接收当前页码数
        $nowPage = input('get.page') ? input('get.page') : 1;
        // 设置每页显示条数
        $limits = config('pagesize');

        // 查询 的字段
        $field = 'a.order_number,b.username,b.telphone,a.business_id,a.service_address,f.company_name a_name,
                  a.combo_money,c.for_core_time,c.renew_date,a.work_order_status,
                  e.engineers_name,a.remarks,a.order_time,a.work_order_id,b.user_id,c.contract_id';
        // 连表
        $join = [
            ['rq_customer b', 'b.user_id = a.user_id','LEFT'],                     // 客户表 对应 工单表
            ['rq_contract c', 'c.contract_id = a.contract_id','LEFT'],             // 合同表 对应 工单表
            ['rq_operation_info d', 'd.o_id = a.operation_id','LEFT'],             // 运营中心表 对应 工单表
            ['rq_engineers e', 'e.engineers_id = a.repair_id','LEFT'],             // 工程人员表 对应 工单表
            ['rq_administrative_info f', 'f.a_id = a.administrative_id','LEFT']    // 行政中心表 对应 工单表
        ];


        //判断用户有没有选择处理状态
        if (!empty($searchObj['workStatus'])) {
            if ($searchObj['workStatus'] == 12) {
                $where['a.work_order_status'] = ['in','5,6,7'];
            }else{
                $where['a.work_order_status'] = $searchObj['workStatus'];
            }
        }
        // 判断用户有没有输入工单号
        if (!empty($searchObj['order_number'])) {
            $where['a.order_number'] = $searchObj['order_number'];
        }
        // 判断用户有没有输入用户名
        if (!empty($searchObj['username'])) {
            $where['b.username'] = $searchObj['username'];
        }
        // 判断用户有没有输入联系电话
        if (!empty($searchObj['telphone'])) {
            $where['b.telphone'] = $searchObj['telphone'];
        }
        // 判断用户有没有输入工程人员
        if (!empty($searchObj['engineers_name'])) {
            $where['e.engineers_name'] = $searchObj['engineers_name'];
        }
        // 判断用户有没有输入工程人员编号
        if (!empty($searchObj['engineers_number'])) {
            $where['e.engineers_number'] = $searchObj['engineers_number'];
        }
        // 判断用户有没有输地区搜索  省 ，
        if (!empty($searchObj['province'])) {
            $where['f.province_id'] = $searchObj['province'];
        }
        // 判断用户有没有输地区搜索 市 ，
        if (!empty($searchObj['city'])) {
            $where['f.city_id'] = $searchObj['city'];
        }
        // 判断用户有没有输地区搜索 区，
        if (!empty($searchObj['area'])) {
            $area = $searchObj['area'];
            $where['f.area_id'] = ['like', "%$area%"];
        }
        // 判断用户有没有输开始日期 // 判断用户有没有输结束日期
        if (!empty($searchObj['startTime']) && !empty($searchObj['endTime'])) {
            $where['a.order_time'] = ['between', [strtotime($searchObj['startTime']), strtotime($searchObj['endTime']) + (60 * 60 * 24 - 1)]];//终止到当天23:59:59
        } else if (!empty($searchObj['startTime'])) {
            $where['a.order_time'] = ['>=', strtotime($searchObj['startTime'])];
        } else if (!empty($searchObj['endTime'])) {
            $where['a.order_time'] = ['<=', strtotime($searchObj['endTime']) + (60 * 60 * 24 - 1)];
        }
        // 查询未被逻辑删除的数据
        $where['a.is_delete'] = 0;
        // 主表
        $dbName = 'rq_work_order';

        // 调用方法
        $data = self::$workModel->getAll($field, $where, $nowPage, $limits, $dbName, $join);
        // 获取总条数
        $count = self::$workModel->getCount($where, $dbName, $join);

        // 获取工单类型
        $type = config('workorder_type');
        // 获取工单状态
        $status = config('work_order_status');
        $workType = ['1' => '续费', '2' => '换芯', '3' => '新装', '4' => '拆机', '5' => '移机',
            '6' => '维修', '7' => '续费+维修', '8' => '换芯+维修', '9' => '移机(拆)', '10' => '移机(装)',
        ];

        // 计算总的页面数
        $allPage = intval(ceil($count / $limits));
        $this->assign('nowPage', $nowPage); //当前页
        $this->assign('allPage', $allPage); //总页数
        $this->assign('count', $count);// 总的条数
        $this->assign('work_order_status', $status);// 工单状态

        // 判断数据是否有值
        if (!empty($data)) {
            // 类型 状态 转换
            foreach ($data as $k => $v) {
                $data[$k]['business_id'] = $workType[$v['business_id']];
                $data[$k]['work_order_status'] = $status[$v['work_order_status']];
                if (strlen($v['for_core_time']) < 5) {
                    $data[$k]['for_core_time'] = '';
                }else{
                    $data[$k]['for_core_time'] = date('Y/m/d', $v['for_core_time']);
                }
                $data[$k]['renew_date'] = $v['renew_date'] ? $v['renew_date'] : '';
                $data[$k]['order_time'] = date('Y/m/d', $v['order_time']);
                $data[$k]['nowPage'] = $nowPage;
                $data[$k]['allPage'] = $allPage;
                $data[$k]['count'] = $count;
                $data[$k]['renewcore'] = $businessid;
            }
        }
        // 返回
        return $data;

    }

    /**
     * @return mixed|\think\response\Json
     *       渲染续费页面
     */
    public function renew()
    {
        // 获取当前登录用户id
        $u_id = session($this->set['db_name'].'uid');

        // 实例化administrative_user表
        $administrativeUserModel = new Administrative();
        $wUser['id'] = $u_id;
        // 查询当前用户属于哪个角色分组
        $atData = $administrativeUserModel->getAdministrativeUser($wUser);
        // 查询登录用户所属哪个角色
        $wGroup['id'] = $atData['groupid'];
        $groupData = $administrativeUserModel->getAdministrativeGroup($wGroup);
        $groupDataId = $groupData['id'];
        // ---------------------------------------------------------------------

        // 续费对应值
        $businessid = 1;
        // 调用renewcore方法处理数据
        $data = $this->renewcore($businessid);

        // 获取工单类型
        $type = config('workorder_type');
        // 获取工单状态
        $status = config('work_order_status');
        $workType = ['1' => '续费', '2' => '换芯', '3' => '新装', '4' => '拆机', '5' => '移机',
            '6' => '维修', '7' => '续费+维修', '8' => '换芯+维修', '9' => '移机(拆)', '10' => '移机(装)',
        ];

        // 判断用户是否有值
        if (input('get.page')) {
            return json($data);
        }

        // 模板赋值 数据，类型
        $this->assign(
            [
                'data' => $data,
                'type' => $type,
                'workType' => $workType,
                'status' => $status,
                'businessid' => $businessid,
                'groupDataId' => $groupDataId
            ]);
        // 调用视图
        return $this->fetch('renewcore');

    }

    /**
     * @return mixed|\think\response\Json
     *       渲染换芯页面
     */
    public function core()
    {
        // 获取当前登录用户id
        $u_id = session($this->set['db_name'].'uid');

        // 实例化administrative_user表
        $administrativeUserModel = new Administrative();
        $wUser['id'] = $u_id;
        // 查询当前用户属于哪个角色分组
        $atData = $administrativeUserModel->getAdministrativeUser($wUser);
        // 查询登录用户所属哪个角色
        $wGroup['id'] = $atData['groupid'];
        $groupData = $administrativeUserModel->getAdministrativeGroup($wGroup);
        $groupDataId = $groupData['id'];
        // ---------------------------------------------------------------------

        // 换芯对应值
        $businessid = 2;
        // 调用renewcore 处理数据
        $data = $this->renewcore($businessid);

        // 获取工单类型
        $type = config('workorder_type');
        // 获取工单状态
        $status = config('work_order_status');
        $workType = ['1' => '续费', '2' => '换芯', '3' => '新装', '4' => '拆机', '5' => '移机',
            '6' => '维修', '7' => '续费+维修', '8' => '换芯+维修', '9' => '移机(拆)', '10' => '移机(装)',
        ];

        // 判断用户是否有值
        if (input('get.page')) {
            return json($data);
        }

        // 模板赋值 数据，类型
        $this->assign(
            [
                'data' => $data,
                'type' => $type,
                'workType' => $workType,
                'status' => $status,
                'businessid' => $businessid,
                'groupDataId' => $groupDataId
            ]);
        // 调用视图
        return $this->fetch('renewcore');

    }

    /**
     * @param $id
     * @return mixed
     *     渲染工单 详情页面
     */
    public function detail()
    {
        Cache::clear();

        // 获取当前登录用户id
        $u_id = session($this->set['db_name'].'uid');

        // 实例化administrative_user表
        $administrativeUserModel = new Administrative();
        $wUser['id'] = $u_id;
        // 查询当前用户属于哪个角色分组
        $atData = $administrativeUserModel->getAdministrativeUser($wUser);
        // 查询登录用户所属哪个角色
        $wGroup['id'] = $atData['groupid'];
        $groupData = $administrativeUserModel->getAdministrativeGroup($wGroup);
        $groupDataId = $groupData['id'];
        // ---------------------------------------------------------------------

        $id = request()->get();
//        dump($id['id']);die();
        // 调用getDetail方法 ， 获取工单详情
        $dataDetail = self::$workModel->getDetail($id['id']);

        // 工单详情 基本信息
        $basicData = $dataDetail[0];
        //  工单信息
        $workData = $dataDetail[1];
        $workData[0]['service_address'] = $workData[0]['province'].$workData[0]['city'].$workData[0]['area'].$workData[0]['service_address'];
        $workData[0]['move_address'] = $workData[0]['move_province'].$workData[0]['move_city'].$workData[0]['move_area'].$workData[0]['move_address'];
//        dump(json_decode(json_encode($workData),true));die();
        // 工单轨迹
        $userData = $dataDetail[2];
        // 设备号
        $equipmentNumber = $dataDetail[3];
        // 配件信息
        $partsData = $dataDetail[4];

        // 处理状态
        $status = config('work_order_status');

        // 类型
        $type = ['1' => '续费', '2' => '换芯', '3' => '新装', '4' => '拆机', '5' => '移机',
            '6' => '维修', '7' => '续费+维修', '8' => '换芯+维修', '9' => '移机(拆)', '10' => '移机(装)',
        ];
        // 客户性质
        $nature = config('nature');
        // 住房性质
        $housing = config('housing_property');
        // 账户状态
        $account_status = ['1' => '正常','2' => '冻结'];
        // 基本信息数据转换
        foreach ($basicData as $k => $v){
            $basicData[$k]['account_status'] = $account_status[$v['account_status']];
        }
        // 工单信息数据转换
        foreach ($workData as $k => $v) {
            $workData[$k]['business_id'] = $type[$v['business_id']];
//            $workData[$k]['work_order_status'] = $status[$v['work_order_status']];
        }

        // 调用视图 将数据赋值给页面
        return $this->fetch('detail',
            [
                'basicData' => $basicData,
                'workData' => $workData,
                'userData' => $userData,
                'equipmentNumber' => $equipmentNumber,
                'partsData' => $partsData,
                'groupDataId' => $groupDataId,
                'work_order_status' => $status,
            ]);

    }

    /**
     * @return \think\response\Json
     *       获取更多工单轨迹数据
     */
    public function getWorkLog()
    {
        // 接收参数
        $workId = input('get.workid');  // 工单ID
        $page = input('get.page');      // 页码数
        $limits = ($page*5).','.(5);
        $where['work_order_id'] = $workId;   // 工单ID
        $data = self::$workModel->getLast($where, $limits);
        // 判断是否有数据
        if (empty($data)) {
            $data[0]['status'] = 0;
            return json($data);
        }
        foreach ($data as $k => $v){
            $data[$k]['operating_time'] = date('Y年m月d日 H:i:s',$v['operating_time']);
            $data[$k]['page'] = $page + 1;
            $data[$k]['status'] = 1;
        }

        return json($data);
    }

    /**
     * @return \think\response\Json
     *     ajax  异步修改 工单 处理状态
     */
    public function status()
    {

        // 获取当前登录用户所属行政中心id
        $a_id = session($this->set['db_name'].'a_id');
        // 实例化行政中心表模型
        $administrativeModel = new Administrative();
        // 条件
        $awhere['a_id'] = $a_id;
        // 查询字段
        $field = ['company_name'];
        // 调用findOne方法获取当前行政中心名称
        $administrativeInfo = $administrativeModel->findOne($awhere,$field);
        $company_name = $administrativeInfo['company_name'] ? $administrativeInfo['company_name'] : '';
        // 获取当前登录用户id
        $u_id = session($this->set['db_name'].'uid');
        // 获取当前登录用户名
        $username = session($this->set['db_name'].'username');

        // 接收ajax请求 获取要修改的状态值
        $data = request()->get();

        // 判断参数是否有效
        if (!empty($data)) {
            // 根据工单ID查询数据判断是否为新装
            $curlWhere['work_order_id'] = $data['work_order_id'];
            $curlData = self::$workModel->getOne($curlWhere);

            // 当工单为新装时
            if ($curlData['business_id'] == 3) {
                // 当状态为 12=>'前台已回访，已完成' 时
                if ($data['work_order_status'] == 12) {

                    /**
                     * 更改逻辑
                     * 家用机直接提交，商用机需要审核
                     */

                    // 判断是否绑定合同---------------------------
                    // 实例化合同表模型
                    $contractModel = new Contract();
                    $cttWhere['contract_id'] = $curlData['contract_id'];
                    $cttData = $contractModel->selectOne($cttWhere);
                    if (empty($cttData)) {
                        return json(['status' => 0, 'message' => '请绑定合同']);
                    }

                    // 查询当前工单的工程人员
//                    $engineersWhere['engineers_id'] = $curlData['repair_id'];
//                    $engineersData = Db::name('engineers')->where($engineersWhere)->find();
                    //查询当前工单讲解人员
                    if (!empty($curlData['engineers_id'])){
                        $engineersWhere['engineers_id'] = $curlData['engineers_id'];
                        $engineersData = Db::name('engineers')->where($engineersWhere)->find();
                        if (empty($engineersData)){
                            return json(['status' => 0, 'message' => '讲解人（工程人员）不存在']);
                        }
                    }
                    // 查询当前工单的合同信息
                    $contractWhere['contract_id'] = $curlData['contract_id'];
                    $contractData = Db::name('contract')->where($contractWhere)->find();

                    if ($contractData['is_special'] == 1){
                        return json(['status' => 0, 'message' => '特殊合同不能提交到业绩系统']);
                    }

                    //判断是否是商用客户
                    if ($contractData['nature'] == 1){
                        //提交到后台审核
                        if ($curlData['audit_status'] == 1){
                            return json(['status' => 0, 'message' => '审核通过，不能重复提交']);
                        }

                        if ($curlData['audit_status'] != 3){
                            $update_info = Db::table('rq_work_order')->where(['work_order_id'=>$curlData['work_order_id']])->update(['audit_status'=>3]);
                            if ($update_info > 0){
                                return json(['status' => 1, 'message' => '修改成功，等待财务审核']);
                            }else{
                                return json(['status' => 0, 'message' => '修改失败，请稍后再试']);
                            }
                        }

                        // 调用方法
                        $result = self::$workModel->editStatus($data,$u_id,$username,$company_name);
                        if ($result){
                            return json(['status' => 1, 'message' => '修改成功，等待财务审核']);
                        }else{
                            return json(['status' => 0, 'message' => '修改失败，请稍后再试']);
                        }
                    }

                    // 查询当前工单的合同客户
                    $customerWhere['user_id'] = $contractData['user_id'];
                    $customerData = Db::name('customer')->where($customerWhere)->find();
                    // 查询当前工单合同推荐人
                    $userWhere['user_id'] = $contractData['introducer_id'];
                    $userData = Db::name('customer')->where($userWhere)->find();
                    //获取合同的申请人
                    $applicant = Db::name('customer')->where(['user_id'=>$contractData['applicant']])->find();
                    // 当推荐人为员工时
//                    if ($userData['is_entry'] == 1) {
                    if (true) {
                        // 查询当前工单设备数量
                        $contractEquipmentWhere['contract_id'] = $contractData['contract_id'];
                        $contractEquipmentWhere['state'] = 1;
                        $contractEquipmentData = Db::name('contract_equipment')->where($contractEquipmentWhere)->count();

                        // post_data数据
                        $post_data['is_explain'] = $contractData['is_explain'];
                        $post_data['achievement_work_order_number'] = $curlData['order_number'];
                        $post_data['achievement_work_order_type'] = $curlData['business_id'];
                        $post_data['engineers_name'] = !empty($curlData['engineers_id']) ? $engineersData['engineers_name'] : '';
                        //$post_data['engineers_number'] = $contractData['eq_count'];//设备数
                        $post_data['engineers_number'] = !empty($curlData['engineers_id']) ? $engineersData['engineers_number'] : '';//工程人员编号
                        $post_data['contract_number'] = $contractData['contract_no'];
                        $post_data['nature'] = $contractData['nature'];//客户类型
                        $post_data['contract_customer'] = $customerData['username'];
                        $post_data['contract_customer_id_card'] = $customerData['id_card'];

                        $post_data['contract_introducer'] = (!empty($contractData['introducer_id']))?$userData['username']:'';//转介绍人

                        $post_data['applicant'] = $applicant['employee_id'];//申请人（员工编号）

                        //如果转介绍入职了，转介绍就是申请人
                        if ($userData['is_entry'] == 1){
                            $post_data['applicant'] = $userData['employee_id'];
                        }

                        $post_data['equipments_number'] = ($contractData['nature'] == 1)?$contractData['eq_count']:$contractEquipmentData;
                        $post_data['request_time'] = time();

                        //数据加密
                        $key = date('Y')."优".date('m')."合".date("d")."一".date("H")."众";
                        $expiry = 10;
                        $request_data['data'] = $this->dataEncode($post_data,$key,$expiry);
                        // crm业绩系统接口地址
                        $url = config('post_api');
                        // 调用post_request发送请求
                        $curResult = post_request($url ,$request_data);

                        if($curResult == false || stripos($curResult,'Error') != false){
                            return json(['status' => 0, 'message' => '网络错误，请稍后','data'=>$curResult]);
                        }
//                        dump($curResult);
//                        exit();
                        $ApiResult = json_decode($curResult);
                        $rank['contract_no']=$contractData['contract_no'];
                        if ($ApiResult->code == 1){
                            //组装合同等级关系数据
                            $tmp=$ApiResult->data;
                            foreach ($tmp as $k=>$v){
                                $rank[$k]=$v;
                            }
                            if(!isset($rank['apply_id'])&&isset($rank['push_id'])){
                                $rank['apply_id']=$rank['push_id'];
                                unset($rank['push_id']);
                            }if(!isset($rank['apply_name'])&&isset($rank['push_name'])){
                                $rank['apply_name']=$rank['push_name'];
                                unset($rank['push_name']);
                            }
                            if($userData){
                                $rank['push_apply_id']=$userData['employee_id'];
                                $rank['push_apply_name']=$userData['username'];
                            }
                            //家用机直接审核通过
                            Db::table('rq_work_order')->where(['work_order_id'=>$curlData['work_order_id']])->update(['audit_status'=>1]);
                            // 调用方法
                            $result = self::$workModel->editStatus($data,$u_id,$username,$company_name);
                            $res = db('contract_rank')->insert($rank);

                            // 判断结果 并返回json数据
                            if ($result == false&&$res == false) {
                                return json(['status' => 0, 'message' => '修改状态失败']);
                            }else{
                                return json(['status' => 1, 'message' => '修改状态成功']);
                            }
                        }else{
                            return json(['status' => 0, 'message' => $ApiResult->msg]);
                        }


                    }else{
                        // 判断是否绑定合同---------------------------
                        // 实例化合同表模型
                        $contractModel = new Contract();
                        $cttWhere['contract_id'] = $curlData['contract_id'];
                        $cttData = $contractModel->selectOne($cttWhere);
                        if (empty($cttData)) {
                            return json(['status' => 0, 'message' => '请绑定合同']);
                        }
                        // 调用方法
                        $result = self::$workModel->editStatus($data,$u_id,$username,$company_name);
                        //$res = db('contract_rank')->insert($rank);
                        // 判断结果 并返回json数据
                        if ($result == false) {
                            return json(['status' => 0, 'message' => '修改状态失败']);
                        }
                        return json(['status' => 1, 'message' => '修改状态成功']);
                    }

                }else{

                    // 调用方法
                    $result = self::$workModel->editStatus($data,$u_id,$username,$company_name);
                    //$res = db('contract_rank')->insert($rank);
                    // 判断结果 并返回json数据
                    if ($result == false) {
                        return json(['status' => 0, 'message' => '修改状态失败']);
                    }
                    return json(['status' => 1, 'message' => '修改状态成功','data'=>$result]);
                }

            }else{

                // 判断是否走最后一步
                if ($data['work_order_status'] == 12) {
                    // 判断是否绑定合同---------------------------
                    // 实例化合同表模型
                    $contractModel = new Contract();
                    $cttWhere['contract_id'] = $curlData['contract_id'];
                    $cttData = $contractModel->selectOne($cttWhere);
                    if (empty($cttData)) {
                        return json(['status' => 0, 'message' => '请绑定合同']);
                    }
                }

                // 调用方法
                $result = self::$workModel->editStatus($data,$u_id,$username,$company_name);
                //$res = db('contract_rank')->insert($rank);
                // 判断结果 并返回json数据
                if ($result == false) {
                    return json(['status' => 0, 'message' => '修改状态失败']);
                }
                    return json(['status' => 1, 'message' => '修改状态成功']);
            }


        }else{
            return json(['status' => 0, 'message' => '参数错误']);
        }

    }

    /**
     * @return \think\response\Json
     *      根据工单id获取当前工单备注信息
     */
    public function getremarks()
    {
        Cache::clear();
        // 或工单id
        $work_order_id = request()->get();
        // 拼接条件
        $map = ['work_order_id' => $work_order_id['work_order_id']];
        // 实例化工单备注关联表
        $workRemarksModel = new WorkOrderRemarks();
        // 调用getAll方法获取当前工单id的工单备注关联表数据
        $data = $workRemarksModel->getAll($map);

        // 获取工单信息
        $status = self::$workModel->getOne($map);
        if (!empty($data)) {
            // 时间转换
            foreach ($data as $k => $v)
            {
                $v['operating_time'] = date('Y/m/d', $v['operating_time']);
                $v['work_order_status'] = $status['work_order_status'];
            }
        }

        // 返回
        return json($data);

    }

    /**
     *    获取所有工程人员
     */
    public function getengineers()
    {
        // 获取当前登录用户所属行政中心id
        $a_id = session($this->set['db_name'].'a_id');

        // 实例化工程人员模型
        $model = new Engineers();

        // 接收搜索数据
        $searchObj = request()->get();
        if (!empty($searchObj)) {
            if (!empty($searchObj['username'])) {
                $where['engineers_name'] = $searchObj['username'];
            }
            if (!empty($searchObj['telphone'])) {
                $where['engineers_phone'] = $searchObj['telphone'];
            }
            if (!empty($searchObj['id_card'])) {
                $where['engineers_idcard'] = $searchObj['id_card'];
            }
        }

        // 获取当前页码数
        $nowPage = input('get.page') ? input('get.page') : 1;
        // 设置每页显示条数
        $limits = config('pagesize');


        // 查询字段
        $field = ['avatar_img,engineers_number,engineers_name,engineers_phone,
                   engineers_idcard,engineers_address,engineers_id'
        ];
        // 条件，未被逻辑删除的工程人员
        $where['is_delete'] = 0;
        // 条件，获取当前行政中心的工程人员
        $where['administrative_id'] = $a_id;
        // 调用getAll方法获取所有工程人员
        $data = $model->getAll($where,$field, $nowPage, $limits);
        // 计算总的数据
        $count = $model->getCount($where);

        // 计算总的页面数
        $allPage = intval(ceil($count / $limits));
        // 循环
        foreach ($data as $k=>$v)
        {
            $data[$k]['nowPage'] = $nowPage;
            $data[$k]['allPage'] = $allPage;
            $data[$k]['count'] = $count;
        }

        return json($data);

    }

    /**
     * @return \think\response\Json
     *    ajax请求，判断工单是否可以指派工程部
     */
    public function judgeworkoder()
    {
        // 接收工单id
        $work_order_id = input('')['work_id'];
        // 接收识别符，index传过来的
        $workstatus = input('')['status'];

        // 遍历
        foreach ($work_order_id as $k => $v)
        {
            // 是on 就退出本次循环
            if ($v == 'on') {
                continue;
            }

            // 判断数据是否有值
            if (!empty($work_order_id)) {
                // 条件
                $where['work_order_id'] = $v;
            }
            $data[] = self::$workModel->getOne($where);
        }
        if ($workstatus == 1) {
            // 遍历判断能否指派
            foreach ($data as $k=>$v)
            {
                if ($v['work_order_status'] < 3) {
                    return json(['status' => 0,'message' => '未确认订单，不能指派']);
                    continue;
                }
            }
        }else{
            // 遍历判断是否已经指派
            foreach ($data as $k=>$v)
            {
                if ($v['work_order_status'] < 3) {
                    return json(['status' => 0,'message' => '未确认订单，不能指派']);
                    continue;
                }
                if ($v['work_order_status'] > 3) {
                    return json(['status' => 0,'message' => '请勿重复指派']);
                    continue;
                }
            }
        }

        return json(['status' => 1,'message' => '可以指派']);

    }

    /**
     * @return string
     *       工单指派工程部
     */
    public function assigndepartment()
    {
        // 获取当前登录用户所属行政中心id
        $a_id = session($this->set['db_name'].'a_id');
        // 实例化行政中心表模型
        $administrativeModel = new Administrative();
        // 条件
        $awhere['a_id'] = $a_id;
        // 查询字段
        $field = ['company_name'];
        // 调用findOne方法获取当前行政中心名称
        $administrativeInfo = $administrativeModel->findOne($awhere,$field);
        $company_name = $administrativeInfo['company_name'] ? $administrativeInfo['company_name'] : '';

        // 获取操作人
        // 获取当前登录用户id
        $u_id = session($this->set['db_name'].'uid');
        // 获取当前登录用户名
        $username = session($this->set['db_name'].'username');

        // 接收工单id
        $work_order_id = input('')['work_id'];
        // 遍历
        foreach ($work_order_id as $k => $v)
        {
            // 是on 就退出本次循环
            if ($v == 'on') {
                continue;
            }

            // 判断数据是否有值
            if (!empty($work_order_id)) {
                // 修改工单状态
                $workOrderData['work_order_status'] = 5;  // 将状态修改为 已指派工程部
                $workOrderData['update_time'] = time();   // 更新时间
                $workOrderData['assignd_time'] = time();  // 指派工程部时间
                // 条件
                $where['work_order_id'] = $v;
            }

            // 调用departmentassign方法修改工单，同时增加一条工单日志表记录
            $result = self::$workModel->departmentassign($where,$workOrderData,$username,$u_id,$company_name);
        }
        // 判断指派结果
        if ($result == false) {
            return json_encode(['status' => 0, 'message' => '指派工程部失败']);
        }
        return json_encode(['status' => 1, 'message' => '指派工程部成功']);

    }

    /**
     * @return \think\response\Json
     *     判断工单是否可以确认
     */
    public function judbatchconfirmation()
    {

        // 接收工单id
        $work_order_id = input('')['work_id'];

        // 判断工单是否是一个数组
        if (is_array($work_order_id) == true) {
            // 遍历
            foreach ($work_order_id as $k => $v)
            {
                // 是on 就退出本次循环
                if ($v == 'on') {
                    continue;
                }

                // 判断数据是否有值
                if (!empty($work_order_id)) {
                    // 条件
                    $where['work_order_id'] = $v;
                }
                $data[] = self::$workModel->getOne($where);
            }

            // 遍历判断是否已经指派
            foreach ($data as $k=>$v)
            {
                if ($v['work_order_status'] == 1) {
                    return json(['status' => 0,'message' => '工单已无效，不能确认']);
                    continue;
                }
                if ($v['work_order_status'] > 2) {
                    return json(['status' => 0,'message' => '请勿重复确认']);
                    continue;
                }
            }
        }else{
            // 工单详情页面确认工单操作
            $where['work_order_id'] = $work_order_id;// 条件
            $data = self::$workModel->getOne($where);
            if ($data['work_order_status'] != 2) {
                return json(['status' => 0,'message' => '工单不能确认']);
            }
        }

        return json(['status' => 1,'message' => '可以指派']);

    }

    /**
     * @return string
     *     前台工单确认
     */
    public function batchconfirmation()
    {
        // 获取当前登录用户所属行政中心id
        $a_id = session($this->set['db_name'].'a_id');
        // 实例化行政中心表模型
        $administrativeModel = new Administrative();
        // 条件
        $awhere['a_id'] = $a_id;
        // 查询字段
        $field = ['company_name'];
        // 调用findOne方法获取当前行政中心名称
        $administrativeInfo = $administrativeModel->findOne($awhere,$field);
        $company_name = $administrativeInfo['company_name'] ? $administrativeInfo['company_name'] : '';

        // 获取操作人
        // 获取当前登录用户id
        $u_id = session($this->set['db_name'].'uid');
        // 获取当前登录用户名
        $username = session($this->set['db_name'].'username');

        // 接收工单id
        $work_order_id = input('')['work_id'];
        // 判断工单是否是一个数组
        if (is_array($work_order_id) == true) {
            // 遍历
            foreach ($work_order_id as $k => $v)
            {
                // 是on 就退出本次循环
                if ($v == 'on') {
                    continue;
                }

                // 判断数据是否有值
                if (!empty($work_order_id)) {
                    // 修改工单状态
                    $workOrderData['work_order_status'] = 3;    // 将状态修改为 前台已确认
                    $workOrderData['update_time'] = time();     // 更新时间
                    $workOrderData['reception_time'] = time();  // 前台确认时间
                    // 条件
                    $where['work_order_id'] = $v;
                }
                // 调用departmentassign方法修改工单，同时增加一条工单日志表记录
                $result = self::$workModel->departmentassign($where,$workOrderData,$username,$u_id,$company_name);
            }
        }else{
            // 修改工单状态
            $workOrderData['work_order_status'] = 3;    // 将状态修改为 前台已确认
            $workOrderData['update_time'] = time();     // 更新时间
            $workOrderData['reception_time'] = time();  // 前台确认时间
            // 条件
            $where['work_order_id'] = $work_order_id;

            // 调用departmentassign方法修改工单，同时增加一条工单日志表记录
            $result = self::$workModel->departmentassign($where,$workOrderData,$username,$u_id,$company_name);
        }

        // 判断指派结果
        if ($result == false) {
            return json_encode(['status' => 0, 'message' => '确认工单失败']);
        }
        return json_encode(['status' => 1, 'message' => '确认工单成功']);

    }

    /**
     * @return \think\response\Json
     *    ajax请求，判断工单是否可以指派工程人员
     */
    public function judgeengineers()
    {
        // 接收工单id
        $work_order_id = input('')['work_order_id'];

        // 遍历
        foreach ($work_order_id as $k => $v)
        {
            // 是on 就退出本次循环
            if ($v == 'on') {
                continue;
            }

            // 判断数据是否有值
            if (!empty($work_order_id)) {
                // 条件
                $where['work_order_id'] = $v;
            }
            $data[] = self::$workModel->getOne($where);
        }
        // 遍历查看是否已经指派过得
        foreach ($data as $k => $v)
        {
            if ($v['work_order_status'] > 7) {
                return json(['status' => 0,'message' => '请勿重复指派']);
                continue;
            }
            if ($v['work_order_status'] < 5) {
                return json(['status' => 0,'message' => '请先指派工程部']);
                continue;
            }
        }
        return json(['status' => 1,'message' => '可以指派']);

    }

    /**
     * @return \think\response\Json
     *         工单指派工程人员
     */
    public function assignengineers()
    {
        // 获取当前登录用户所属行政中心id
        $a_id = session($this->set['db_name'].'a_id');
        // 实例化行政中心表模型
        $administrativeModel = new Administrative();
        // 条件
        $awhere['a_id'] = $a_id;
        // 查询字段
        $field = ['company_name'];
        // 调用findOne方法获取当前行政中心名称
        $administrativeInfo = $administrativeModel->findOne($awhere,$field);
        $company_name = $administrativeInfo['company_name'] ? $administrativeInfo['company_name'] : '';

        // 获取操作人
        // 获取当前登录用户id
        $u_id = session($this->set['db_name'].'uid');
        // 获取当前登录用户名
        $username = session($this->set['db_name'].'username');

        // 接收工单跟工程人员信息
        $workEngineers = request()->get();
        // 接收工单id
        $workOrderID = input('')['work_order_id'];
        foreach ($workOrderID as $k=>$v)
        {
            // 是on 就退出本次循环
            if ($v == 'on') {
                continue;
            }
            // 判断数据是否有值
            if (empty($workEngineers)) {
                $this->error('参数错误');
            }else{
                // 获取工单id
                $work_order_id = $v;                                     // 工单id

                // 获取工程人员信息
                $engineers_id = $workEngineers['engineers_id'];          // 工程人员id
                $engineers_name = $workEngineers['engineers_name'];      // 工程人员姓名
                $engineers_phone = $workEngineers['engineers_phone'];    // 工程人员电话
                $engineers_number = $workEngineers['engineers_number'];  // 工程人员编号

                // 工单修改数据为指派
                $editData['work_order_status'] = 7;         // 修改工单状态为已指派
                $editData['repair_id'] = $engineers_id;     // 维修人员id
                $editData['update_time'] = time();          // 更新时间
                $editData['assigne_time'] = time();         // 指派工程人员时间
                // 条件
                $where['work_order_id'] = $work_order_id;
            }

            // 调用workassisn方法修改工单，同时增加一条工单日志表记录
            $result = self::$workModel->workassign($where,$editData,$u_id,$engineers_name,$username,$company_name);
        }
        // 判断结果
        if ($result == false) {
            return json(['status' => 0, 'message' => '指派工程人员失败']);
        }
            return json(['status' => 1, 'message' => '指派工程人员成功']);

    }

    /**
     * @return mixed
     *       渲染新增工单页面
     */
    public function workorderadd()
    {
//        $bug = input('bug') ? input('bug') : 2;
//        if ($bug != 1){
//            $this->error('正在维护，请稍后');
//        }

        // 获取当前登录用户所属行政中心id
        $a_id = session($this->set['db_name'].'a_id');
        // 实例化行政中心表模型
        $administrativeModel = new Administrative();
        // 条件
        $where['a_id'] = $a_id;
        // 查询字段
        $field = ['province_id,city_id,area_id'];
        // 调用findOne方法获取当前行政中心的三级联动
        $data = $administrativeModel->findOne($where,$field);
        // 区县拿第一个
        $data['area_id'] = explode(',',$data['area_id'])[0];

        // 获取工单类型
        $type = config('workorder_type');

        // 实例化用户表模型
        $customerModel = new Customer();
        //获取地址三级联动
        $province = $customerModel->areasProvince();
        $city = $customerModel->areasCity($data['province_id']);
        $area = $customerModel->areaName($data['city_id']);

        $e_field = '
            engineers_id,
            engineers_name,
            engineers_number,
            engineers_phone,
            engineers_status
        ';
        $engineers = Db::table('rq_engineers')->where(['is_delete'=>0])->field($e_field)->select();

        // 调用视图，将数据赋值给页面
        return $this->fetch('workorderadd',
            [
                'type' => $type,
                'province' => $province,
                'city' => $city,
                'area' => $area,
                'data' => $data,
                'engineers' => $engineers,
            ]);

    }

    /**
     * @return \think\response\Json
     *     新增工单 获取用户数据
     */
    public function getuser()
    {

        // 获取当前登录用户所属行政中心id
        $a_id = session($this->set['db_name'].'a_id');

        // 实例化模型 获取所有用户
        $customerModel = new Customer();

        // 接收搜索数据
        $searchObj = request()->get();
        if (!empty($searchObj)) {
            if (!empty($searchObj['username'])) {
                $where['username'] = $searchObj['username'];
            }
            if (!empty($searchObj['telphone'])) {
                $where['telphone'] = $searchObj['telphone'];
            }
            if (!empty($searchObj['id_card'])) {
                $where['id_card'] = $searchObj['id_card'];
            }
        }

        // 获取当前页码数
        $nowPage = input('get.page') ? input('get.page') : 1;
        // 设置每页显示条数
        $limits = config('pagesize');
        // 查询字段
        $field = [
            'b.telphone,username,b.id_card,b.account_status,b.user_id'
        ];
        // 查询未被逻辑删除的
        $where['is_delete'] = 0;
        // 主表
        $dbName = 'rq_customer_administrative_center';
        $join  = [
            ['rq_customer b','b.user_id = a.user_id']    // 客户表对应客户与行政中心关联表
            ];
        // 当前行政中心ID
        $where['administrative_id'] = $a_id;
        // 调用getList获取所有用户
        $data = $customerModel->getAll($where,$nowPage,$limits,$field,$dbName,$join);

        // 计算总的数据
        $count = $customerModel->getCount($where,$join);

        // 计算总的页面数
        $allPage = intval(ceil($count / $limits));

        $account_status =  ['1' => '正常', '2' => '冻结'];
        foreach ($data as $k=>$v)
        {
            $data[$k]['account_status'] = $account_status[$v['account_status']];
            $data[$k]['nowPage'] = $nowPage;
            $data[$k]['allPage'] = $allPage;
            $data[$k]['count'] = $count;
        }

        // 返回
        return json($data);

    }

    /**
     * @return \think\response\Json
     *     新增工单 获取合同数据
     */
    public function getcontract()
    {

        // 接收合同编号
        $contract_no = input('get.contract_no');
        if (!empty($contract_no)) {
            $where['contract_no'] = $contract_no;
        }

        // 接收被选中的用户id
        $userid = input('get.userid');
        if (!empty($userid)) {
            $where['user_id'] = $userid;

        // 实例化合同模型
        $contractModel = new Contract();

        // 获取当前页码数
        $nowPage = input('get.page') ? input('get.page') : 1;
        // 设置每页显示条数
        $limits = config('pagesize');

        // 查询字段
        $field = [
            'contract_no,installed_time,renew_date,exire_date,contract_money,contract_status,contract_id,user_id,province_code,city_code,area_code,address,is_explain'
        ];

        // 查询未被逻辑删除的数据
        $where['is_delete'] = 0;
        // 查询合同状态为正常的数据
        $where['contract_status'] = 1;

        // 调用get_id_all方法获取当前id对应的所有合同
        $data = $contractModel->get_id_all($where,$field,$nowPage,$limits);
        // 查询总的数据
        $count = $contractModel->getCount($where);
        // 计算总的页面数
        $allPage = intval(ceil($count / $limits));


        // 合同状态
        $status = config('contract_status');

        if (!empty($data)) {
            // 实例化合同设备关联表模型
            $contractEquipmentModel = new ContractEquipment();
            foreach ($data as $k=>$v)
            {
                // 获取合同对应的合同台数
                $data[$k]['sbcount'] = $contractEquipmentModel->get_id_count($v['contract_id']);
                $data[$k]['installed_time'] = date('Y/m/d',$v['installed_time']);
                $data[$k]['exire_date'] = date('Y/m/d',$v['exire_date']);
                $data[$k]['contract_status'] = $status[$v['contract_status']];
                $data[$k]['nowPage'] = $nowPage;
                $data[$k]['allPage'] = $allPage;
                $data[$k]['count'] = $count;
                $ctEqWhere['contract_id'] = $v['contract_id'];
                $data[$k]['equipmentCount'] = $contractModel->getEquipmentCount($ctEqWhere) ? $contractModel->getEquipmentCount($ctEqWhere) : 0;
            }
        }

        }else{
            // 如果没有用户，合同为空
            $data = '';
        }
//        dump($data);die();
        return json($data);

    }

    /**
     * @return \think\response\Json
     *     新增工单 获取装机型号+设备编号
     */
    public function getequipments($contractId = '')
    {
        // 获取合同id
        $contract_id = input('get.contract_id');

        // 实例化合同设备关联表模型
        $contractEquipmentModel = new ContractEquipment();
        // 查询字段
        $field = ['id,equipments_id,equipments_number'];
        // 判断是否有数据
        if (!empty($contractId)) {
            // 根据合同id查询
            $where['contract_id'] = $contractId;
        }else{
            // 根据合同id查询
            $where['contract_id'] = $contract_id;
        }

        // 调用get_id_all方法查询 获取设备id跟设备编号
        $equipment = $contractEquipmentModel->get_id_all($where,$field);

        // 实例化设备表模型
        $equipmentModel = new Equipments();
        // 查询字段
        $fields = ['equipments_id,equipments_name'];
        // 循环取出查询设备
        foreach ($equipment as $k => $v)
        {
            $equipments[] = $equipmentModel->get_id_all($v['equipments_id'],$fields);
        }
        if (!empty($equipment)) {
            // 将装机设备 跟 设备编号合并
            foreach ($equipments as $k => $v){
                foreach ($v as $key => $val){
                    // 将装机设备 跟 设备编号合并
                    $val['equipments_number'] = $equipment[$k]['equipments_number'];
                    $val['id'] = $equipment[$k]['id'];
                    $equipmentsNumber[] = $val;
                }
            }
        }else{
            $equipmentsNumber = '';
        }


        if (!empty($contractId)) {
            return $equipmentsNumber;
        }else{
            // 返回
            return json($equipmentsNumber);
        }


    }

    /**
     *    处理新增工单方法
     */
    public function addto()
    {
        // 获取当前登录用户所属行政中心id
        $a_id = session($this->set['db_name'].'a_id');
        // 实例化行政中心表模型
        $administrativeModel = new Administrative();
        // 条件
        $awhere['a_id'] = $a_id;
        // 查询字段
        $field = ['company_name'];
        // 调用findOne方法获取当前行政中心名称
        $administrativeInfo = $administrativeModel->findOne($awhere,$field);
        $company_name = $administrativeInfo['company_name'] ? $administrativeInfo['company_name'] : '';


        // 获取当前登录用户id
        $u_id = session($this->set['db_name'].'uid');
        // 获取当前登录用户名
        $username = session($this->set['db_name'].'username');
        // 实例化行政中心表模型
        $administrative_infoModel = new Administrative();
        // 条件拼接
        $where['a_id'] = $a_id;
        // 调用findOne方法查询 它所属运营中心id
        $administrative = $administrative_infoModel->findOne($where);

        // 接收新增工单数据
        $data = request()->post();
//        dump($data);die();
        // 声明一个空数组用来装工单表数据
        $wordData = [];
        // 判断数据是否有值
        if (empty($data)) {
            $this->error('参数错误');
        }else{
            // 获取工单号,自动生成
            $workOrderNumber =  workOrderNumber();
            // 当业务类型为移机的时候
            if ($data['businessid'] == 5) {
                $wordData['business_id'] = $data['shift'];                 // 移机类型
                if ($data['isuser'] == 1) {                                // 是否同意用户，1是2否
                    // 实例化合同设备关联表模型
                    $contractEquipmentModel = new ContractEquipment();
                    // 实例化合同表模型
                    $contractModel = new Contract();
                    $map['contract_id'] = $data['contract_id'];
                    // 获取合同地址
                    $contractData = $contractModel->getOne($map);
                    // 获取设备地址
                    $equipments_address  = $contractEquipmentModel->getOne($map);
                    $service_address = $equipments_address['equipments_address'] ? $equipments_address['equipments_address'] : '';
                    $wordData['province'] = $contractData['province'];             // 服务地址省
                    $wordData['city'] = $contractData['city'];                     // 服务地址市
                    $wordData['area'] = $contractData['area'];                     // 服务地址区
                    $wordData['province_code'] = $contractData['province_code'];   // 服务地址省id
                    $wordData['city_code'] = $contractData['city_code'];           // 服务地址市id
                    $wordData['area_code'] = $contractData['area_code'];           // 服务地址区id
                    $wordData['service_address'] = $service_address;               // 获取设备地址当做服务地址
                }else{
                    $wordData['province'] = $data['userprovince'];             // 服务地址省
                    $wordData['city'] = $data['usercity'];                     // 服务地址市
                    $wordData['area'] = $data['userarea'];                     // 服务地址区
                    $wordData['province_code'] = $data['province_code'];       // 服务地址省id
                    $wordData['city_code'] = $data['city_code'];               // 服务地址市id
                    $wordData['area_code'] = $data['area_code'];               // 服务地址区id
                    $wordData['service_address'] = $data['user_address'];      // 服务详细地址
                }
                $wordData['isuser'] = $data['isuser'];                     // 是否同一用户
                $wordData['move_province'] = $data['moveprovince'];        // 移机地址省
                $wordData['move_city'] = $data['movecity'];                // 移机地址市
                $wordData['move_area'] = $data['movearea'];                // 移机地址区
                $wordData['move_province_code'] = $data['province_id'];    // 移机地址省id
                $wordData['move_city_code'] = $data['city_id'];            // 移机地址市id
                $wordData['move_area_code'] = $data['area_id'];            // 移机地址区id
                $wordData['move_address'] = $data['service_address'];      // 移机地址
            }else{
                $wordData['business_id'] = $data['businessid'];            // 业务类型id
                $wordData['province'] = $data['userprovince'];             // 服务地址省
                $wordData['city'] = $data['usercity'];                     // 服务地址市
                $wordData['area'] = $data['userarea'];                     // 服务地址区
                $wordData['province_code'] = $data['province_code'];       // 服务地址省id
                $wordData['city_code'] = $data['city_code'];               // 服务地址市id
                $wordData['area_code'] = $data['area_code'];               // 服务地址区id
                $wordData['service_address'] = $data['user_address'];      // 服务详细地址
            }
                $wordData['user_id'] = $data['user_id'];                   // 用户id
                $wordData['contract_id'] = $data['contract_id'];           // 合同id
                $wordData['administrative_id'] = $a_id;                    // 行政中心id
                $wordData['operation_id'] = $administrative['operation'];  // 运营中心id
                $wordData['combo_money'] = $data['combo_money'];           // 费用
                $wordData['reception_user'] = 1;                           // 1表示用户下单
                $wordData['work_order_status'] = 2;                        // 工单状态 新增工单，默认为2 -> 未处理
                $wordData['order_time'] = time();                          // 下单时间
                $wordData['update_time'] = time();                         // 更新时间
                $wordData['order_number'] = $workOrderNumber;              // 工单号
                $wordData['remarks'] = $data['remarks'] ? $data['remarks'] : '新增工单'; // 备注
                $wordData['contact_number'] = $data['contact_number'];     // 下单时联系电话
                $wordData['contacts'] = $data['contacts'];                 // 下单时联系人
                $wordData['engineers_id'] = (isset($data['engineers']) && !empty($data['engineers'])) ? $data['engineers'] : '';            // 讲解的工程人员ID
        }
        //当工单为新装时，验证合同工单唯一
        if ($wordData['business_id'] == 3){
            $check_order = self::$workModel->getOne(['contract_id'=>$wordData['contract_id'],'business_id'=>3]);
            if ($check_order){
                $this->error('该合同已创建新装工单，请勿重复创建');
                return false;
            }
        }

        // 调用insertId方法 增加一条工单数据，同时增加一条工单日志数据
        $result = self::$workModel->insertId($wordData,$username,$u_id,$data['equipmentsname'],$company_name);

        // 判断结果
        if ($result == false) {
             $this->error('添加失败');
        }
            $this->success('添加成功','/administrative/workorder/unassigned');

    }

    /**
     * @return \think\response\Json
     *     新增工单，获取工程部
     */
    public function getdepartment()
    {
        // 获取当前登录用户所属行政中心的id
        $a_id = session($this->set['db_name'].'a_id');

        // 实例化行政中心表模型
        $administrative_infoModel = new Administrative();
        // 条件拼接
        $where['a_id'] = $a_id;
        // 调用findOne方法查询
        $data = $administrative_infoModel->findOne($where);
        $area_name = explode(',',$data['area_name']);
        return json($area_name);

    }

    /**
     * @return mixed
     *      渲染工单修改页面
     */
    public function edit()
    {
        // 接收工单id
        $wid = input('')['wid'];
        // 客户id
        $uid = input('')['uid'];
        // 合同id
        $cid = input('')['cid'];
        // 判断从工单列表页，还是续费换芯页面点击的修改，1为续费页，2为换芯页，3为工单未指派页，4为工单已指派页
        $who = input('')['who'] ? input('')['who'] : '';

        // 实例化用户表模型
        $userModel = new Customer();

        // 查出工单信息，用于回显
        $where['work_order_id'] = $wid;
        //$workData = self::$workModel->find($where);
        $workData = db('work_order')->where($where)->find();

//dump(json_decode(json_encode($workData),true));die();
        //获取地址三级联动
        $province = $userModel->areasProvince();
        $city = $userModel->areasCity($workData['province_code']);
        $area = $userModel->areaName($workData['city_code']);

        // 获取工单业务类型
        $workType = config('workorder_type');
        // 当前工单业务类型
        $business = $workData['business_id'];
        if ($workData['business_id'] == 9 || $workData['business_id'] == 10) {
            $workData['business_id'] = 5;
        }
        // 当工单为新装时
        if ($workData['business_id'] == 3) {
            // 判断是否绑定合同 给他一个标识符 1为已绑定合同,0为没有绑定合同
            if ($cid == 'null') {
                // 没有绑定
                $identifier = 0;
            }else{
                // 绑定了
                $identifier = 1;
            }
        }else{
            $identifier = '';
        }


        // 查出客户信息，用于回显
        $uwhere['user_id'] = $uid;
        // 实例化用户表模型
        $userData = $userModel->selectOne($uwhere);

        // 查出合同信息，用于回显
        $cwhere['contract_id'] = $cid;
        // 实例化合同模型
        $contractModel = new Contract();
        $contractData = $contractModel->selectData($cwhere);
        foreach ($contractData as $k => $v)
        {
            $contractData[$k]['installed_time'] = date('Y/m/d',$v['installed_time']);
            $contractData[$k]['exire_date'] = date('Y/m/d',$v['exire_date']);
        }

        if (!empty($contractData)) {
            // 调用getequipments方法，获取当前合同下的所有装机型号跟设备编号
            $equipmentsNumber = $this->getequipments($contractData[0]['contract_id']);
        }
        if (empty($equipmentsNumber)) {
            $equipmentsNumber = '';
        }
        //dump(json_decode(json_encode($equipmentsNumber),true));die();
        // 实例化工单设备关联表
        $workEquipmentModel = new WorkEquipment();
        $ewhere['work_order_id'] = $workData['work_order_id'];
        // 根据工单ID获取合同设备关联表ID
        $workEquipmentData = $workEquipmentModel->getOne($ewhere);

        // 实例化合同设备关联表模型
        $contractEquipmentModel = new ContractEquipment();
        $cewhere['id'] = $workEquipmentData['contract_equipment_id'];
        $contractEquipmentData = $contractEquipmentModel->getOne($cewhere);
        // 获取当前工单设备编号
        $equipments_number = $contractEquipmentData['equipments_number'];

        // 实例化设备表模型
        $equipmentsModel = new Equipments();
        $eqwhere['equipments_id'] = $contractEquipmentData['equipments_id'];
        $equipmentsData = $equipmentsModel->selectOne($eqwhere);
        $equipments_name = $equipmentsData['equipments_name'];

        // 调用视图,将数据赋值给页面
        return $this->fetch('edit',
            [
                'workData' => $workData,                     // 工单数据
                'userData' => $userData,                     // 客户数据
                'contractData' => $contractData,             // 合同数据
                'workType' => $workType,                     // 工单类型
                'business' => $business,                     // 当前工单类型
                'province' => $province,                     // 省
                'city' => $city,                             // 市
                'area' => $area,                             // 县
                'equipmentsNumber' => $equipmentsNumber,     // 合同下的所有装机型号+设备编号
                'equipments_number' => $equipments_number,   // 当前工单的设备编号
                'equipments_name' => $equipments_name,       // 当前工单的装机型号
                'who' => $who,                               // 页面标识数
                'identifier' => $identifier,                 // 判断有没有绑定合同标识符
            ]);

    }

    /**
     *      处理工单修改数据
     */
    public function modify()
    {
        // 获取当前登录用户所属行政中心id
        $a_id = session($this->set['db_name'].'a_id');
        // 实例化行政中心表模型
        $administrativeModel = new Administrative();
        // 条件
        $awhere['a_id'] = $a_id;
        // 查询字段
        $field = ['company_name'];
        // 调用findOne方法获取当前行政中心名称
        $administrativeInfo = $administrativeModel->findOne($awhere,$field);
        $company_name = $administrativeInfo['company_name'] ? $administrativeInfo['company_name'] : '';

        // 获取当前登录用户id
        $u_id = session($this->set['db_name'].'uid');
        // 获取当前登录用户名
        $username = session($this->set['db_name'].'username');

        // 接收修改的数据
        $data = request()->post();
//        dump($data);die();

        // 声明一个空数组用来装工单数据
        $workData = [];
        // 判断数据是否有值
        if (empty($data)) {
            $this->error('参数错误');
        }else{
            // 当业务类型为移机时
            if ($data['businessid'] == 5) {
                $workData['business_id'] = $data['shift'];                 // 移机类型
                $workData['isuser'] = $data['isuser'];                     // 是否同一用户
                $workData['move_province'] = $data['moveprovince'];        // 移机地址省
                $workData['move_city'] = $data['movecity'];                // 移机地址市
                $workData['move_area'] = $data['movearea'];                // 移机地址区
                $workData['move_province_code'] = $data['province_id'];    // 移机地址省id
                $workData['move_city_code'] = $data['city_id'];            // 移机地址市id
                $workData['move_area_code'] = $data['area_id'];            // 移机地址区id
                $workData['move_address'] = $data['service_address'];      // 移机地址拼接
            }else{
                $workData['business_id'] = $data['businessid'];            // 业务类型
            }
                $workData['user_id'] = $data['user_id'];                   // 用户id
                $workData['contract_id'] = $data['contract_id'];           // 合同id
                $workData['combo_money'] = $data['combo_money'];           // 费用
                $workData['update_time'] = time();                         // 更新时间
                $workData['province'] = $data['userprovince'];             // 服务地址省
                $workData['city'] = $data['usercity'];                     // 服务地址市
                $workData['area'] = $data['userarea'];                     // 服务地址区
                $workData['province_code'] = $data['province_code'];       // 服务地址省id
                $workData['city_code'] = $data['city_code'];               // 服务地址市id
                $workData['area_code'] = $data['area_code'];               // 服务地址区id
                $workData['service_address'] = $data['user_address'];      // 服务详细地址
                $workData['remarks'] = $data['remarks'] ? $data['remarks'] : '修改工单'; // 备注
                $workData['contact_number'] = $data['contact_number'];     // 下单时联系电话
                $workData['contacts'] = $data['contacts'];                 // 下单时联系人
        }

//        dump(json_decode(json_encode($workData),true));die();
        // 调用modify方法，完成一次工单修改
        $result = self::$workModel->modify($workData,$data,$u_id,$username,$company_name);

        // 1为续费页，2为换芯页，3为工单未指派页，4为工单已指派页
        if ($data['who'] == 1) {
            // 判断结果
            if ($result == false) {
                $this->error('修改失败');
            }
            $this->success('修改成功','/administrative/workorder/renew');
        }
        if ($data['who'] == 2) {
            // 判断结果
            if ($result == false) {
                $this->error('修改失败');
            }
            $this->success('修改成功','/administrative/workorder/core');
        }
        if ($data['who'] == 3) {
            // 判断结果
            if ($result == false) {
                $this->error('修改失败');
            }
            $this->success('修改成功','/administrative/workorder/unassigned');
        }
        if ($data['who'] == 4) {
            // 判断结果
            if ($result == false) {
                $this->error('修改失败');
            }
            $this->success('修改成功','/administrative/workorder/assigned');
        }

    }

    /**
     * 导出工单
     * @author ligang
     * @date 2018/6/6 17:15
     */
    public function export()
    {
//        $this->error('抱歉，正在努力的开发中！');

        set_time_limit(0);
        ini_set("max_execution_time", "0");
        ob_end_clean();//清除缓冲区,避免乱码
        ob_start();
        header('Content-Type:text/html;charset=utf-8');
        $this->assign('work_order_status',config('work_order_status'));
        //只能导出当前行政中心的工单
        if (request()->isPost()){
            $a_id = session($this->set['db_name'].'a_id');
            $param = input();
            $start_time = isset($param['datetimeStart'])?$param['datetimeStart']:'';
            $end_time = isset($param['datetimeEnd'])?$param['datetimeEnd']:'';
            $state = isset($param['state'])?$param['state']:'';
            $where = [];
            //时间条件
            $time = [];
            if (!empty($start_time)){
                if (!empty($end_time)){
                    $where['rq_work_order.order_time'] = ['BETWEEN',[strtotime($start_time),strtotime($end_time) + 86400]];
                }else{
                    $where['rq_work_order.order_time'] = ['BETWEEN',[strtotime($start_time),time() + 86400]];
                }
                $time = $where['rq_work_order.order_time'];
            }else{
                if (!empty($end_time)){
                    $where['rq_work_order.order_time'] = ['BETWEEN',[time(),strtotime($end_time) + 86400]];
                    $time = $where['rq_work_order.order_time'];
                }
            }

            if (!empty($state)){
                $where['rq_work_order.work_order_status'] = ['IN',$state];
            }

            $where['rq_work_order.administrative_id'] = $a_id;
            $where['rq_work_order.is_delete'] = 0;

            //获取数据
            $join = [
                ['rq_work_order','rq_contract_equipment.contract_id = rq_work_order.contract_id','LEFT'],
                ['rq_customer','rq_work_order.user_id = rq_customer.user_id','LEFT'],
                ['rq_contract','rq_work_order.contract_id = rq_contract.contract_id','LEFT'],
                ['rq_equipments','rq_contract_equipment.equipments_id = rq_equipments.equipments_id','LEFT'],
                ['rq_engineers','rq_work_order.repair_id = rq_engineers.engineers_id','LEFT']
            ];
            $field = '
                rq_work_order.order_number,
                rq_work_order.business_id,
                rq_work_order.combo_money,
                rq_work_order.reception_user,
                rq_work_order.work_order_status,
                rq_work_order.order_time,
                rq_work_order.assigne_time,
                rq_work_order.assignd_time,
                rq_work_order.reception_time,
                rq_work_order.contact_number,
                rq_work_order.contacts,
                rq_customer.username,
                rq_customer.telphone,
                rq_customer.id_card,
                rq_customer.user_address,
                rq_contract.contract_no,
                rq_equipments.equipments_name,
                rq_engineers.engineers_name,
                rq_engineers.engineers_phone
            ';
            $data = Db::table('rq_contract_equipment')->where($where)->join($join)->field($field)->select();
            //执行导出操作
            if (empty($data)){
                $this->error('没有数据可以导出');
                exit();
            }
            //转化数据
            foreach ($data as $key=>$value){
                $data[$key]['order_time'] = date('Y-m-d H:i:s',$value['order_time']);
                $data[$key]['assigne_time'] = date('Y-m-d H:i:s',$value['assigne_time']);
                $data[$key]['assignd_time'] = date('Y-m-d H:i:s',$value['assignd_time']);
                $data[$key]['reception_time'] = date('Y-m-d H:i:s',$value['reception_time']);
                $data[$key]['business_id'] = isset(config('workorder_type')[$value['business_id']])?config('workorder_type')[$value['business_id']]:'未知';
                $data[$key]['work_order_status'] = isset(config('work_order_status')[$value['work_order_status']])?config('work_order_status')[$value['work_order_status']]:'未知';
                switch ($value['reception_user']){
                    case 0:
                        $data[$key]['reception_user'] = '前台';
                        break;
                    case 1:
                        $data[$key]['reception_user'] = '用户';
                        break;
                    case 2:
                        $data[$key]['reception_user'] = '系统';
                        break;
                    default:
                        $data[$key]['reception_user'] = '未知';
                }
            }
//            dump($data);
//            exit();
            $a_name = Db::table('rq_administrative_info')->where(['a_id'=>$a_id])->field('company_name')->find();
            $this->orderExport($data,$time,isset($a_name['company_name'])?$a_name['company_name']:'');
            exit();
        }

        return $this->fetch('workorder/export');
    }

    protected function orderExport($data,$time,$a_name)
    {
        $filename = $a_name.'工单' . '-' . date('Y年m月d日H时i分s秒', time()) . ".xls";
        $title = '';
        if (!empty($time)){
            $title .= date('Y-m-d',$time[1][0]).' 至 '.date('Y-m-d',$time[1][1]).' 的';
        }
        $title .= '工单列表';
        Vendor('phpexcel.phpexcel.Classes.PHPExcel');
        $PHPExcel = new \PHPExcel();
        //设置信任
        $PHPExcel->getProperties()->setCreator("ctos")
            ->setLastModifiedBy("ctos")
            ->setTitle("Office 2007 XLSX Test Document")
            ->setSubject("Office 2007 XLSX Test Document")
            ->setDescription("Test document for Office 2007 XLSX, generated using PHP classes.")
            ->setKeywords("office 2007 openxml php")
            ->setCategory("Test result file");
        //设置列宽
        $PHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(14);
        $PHPExcel->getActiveSheet()->getColumnDimension('B')->setWidth(14);
        $PHPExcel->getActiveSheet()->getColumnDimension('C')->setWidth(14);
        $PHPExcel->getActiveSheet()->getColumnDimension('D')->setWidth(14);
        $PHPExcel->getActiveSheet()->getColumnDimension('E')->setWidth(28);
        $PHPExcel->getActiveSheet()->getColumnDimension('F')->setWidth(20);
        $PHPExcel->getActiveSheet()->getColumnDimension('G')->setWidth(20);
        $PHPExcel->getActiveSheet()->getColumnDimension('H')->setWidth(25);
        $PHPExcel->getActiveSheet()->getColumnDimension('I')->setWidth(25);
        $PHPExcel->getActiveSheet()->getColumnDimension('J')->setWidth(25);
        $PHPExcel->getActiveSheet()->getColumnDimension('K')->setWidth(25);
        $PHPExcel->getActiveSheet()->getColumnDimension('L')->setWidth(30);
        $PHPExcel->getActiveSheet()->getColumnDimension('M')->setWidth(20);
        $PHPExcel->getActiveSheet()->getColumnDimension('N')->setWidth(30);
        $PHPExcel->getActiveSheet()->getColumnDimension('O')->setWidth(25);
        $PHPExcel->getActiveSheet()->getColumnDimension('P')->setWidth(30);
        $PHPExcel->getActiveSheet()->getColumnDimension('Q')->setWidth(20);
        $PHPExcel->getActiveSheet()->getColumnDimension('R')->setWidth(20);
        $PHPExcel->getActiveSheet()->getColumnDimension('S')->setWidth(30);
        //合并单元格
        $PHPExcel->getActiveSheet()->mergeCells('A1:S1');
        //设置高度
        $PHPExcel->getActiveSheet()->getRowDimension(1)->setRowHeight(50);
        //设置标题
        $PHPExcel->getActiveSheet()->setCellValue('A1',$title);
        //设置表头
        $PHPExcel->getActiveSheet()->setCellValue('A2', '工单编号');
        $PHPExcel->getActiveSheet()->setCellValue('B2', '工单类型');
        $PHPExcel->getActiveSheet()->setCellValue('C2', '工单费用');
        $PHPExcel->getActiveSheet()->setCellValue('D2', '工单创建');
        $PHPExcel->getActiveSheet()->setCellValue('E2', '工单状态');
        $PHPExcel->getActiveSheet()->setCellValue('F2', '下单时间');
        $PHPExcel->getActiveSheet()->setCellValue('G2', '工程人员姓名');
        $PHPExcel->getActiveSheet()->setCellValue('H2', '工程人员电话');
        $PHPExcel->getActiveSheet()->setCellValue('I2', '前台确认时间');
        $PHPExcel->getActiveSheet()->setCellValue('J2', '指派工程部时间');
        $PHPExcel->getActiveSheet()->setCellValue('K2', '指派工程人员时间');
        $PHPExcel->getActiveSheet()->setCellValue('L2', '工单联系人');
        $PHPExcel->getActiveSheet()->setCellValue('M2', '工单联系电话');
        $PHPExcel->getActiveSheet()->setCellValue('N2', '合同姓名');
        $PHPExcel->getActiveSheet()->setCellValue('O2', '合同联系电话');
        $PHPExcel->getActiveSheet()->setCellValue('P2', '合同身份证');
        $PHPExcel->getActiveSheet()->setCellValue('Q2', '合同编号');
        $PHPExcel->getActiveSheet()->setCellValue('R2', '用户地址');
        $PHPExcel->getActiveSheet()->setCellValue('S2', '设备型号');
        //设置字体样式
        $PHPExcel->getActiveSheet()->getStyle('A1')->getFont()->setName('黑体');
        $PHPExcel->getActiveSheet()->getStyle('A1')->getFont()->setSize(20);
        $PHPExcel->getActiveSheet()->getStyle('A1')->getFont()->setBold(true);
        $PHPExcel->getActiveSheet()->getStyle('A2:S2')->getFont()->setName('微软雅黑');
        $PHPExcel->getActiveSheet()->getStyle('A2:S2')->getFont()->setSize(14);
        $PHPExcel->getActiveSheet()->getStyle('A2:S2')->getFont()->setBold(true);

        foreach ($data as $k => $v) {
            //设置单元格值
            $PHPExcel->getActiveSheet()->setCellValue('A' . ($k + 3), $v['order_number']);
            $PHPExcel->getActiveSheet()->setCellValue('B' . ($k + 3), $v["business_id"]);
            $PHPExcel->getActiveSheet()->setCellValue('C' . ($k + 3), $v['combo_money'].'元');
            $PHPExcel->getActiveSheet()->setCellValue('D' . ($k + 3), $v['reception_user']);
            $PHPExcel->getActiveSheet()->setCellValue('E' . ($k + 3), $v['work_order_status']);
            $PHPExcel->getActiveSheet()->setCellValue('F' . ($k + 3), $v['order_time']);
            $PHPExcel->getActiveSheet()->setCellValue('G' . ($k + 3), $v['engineers_name']);
            $PHPExcel->getActiveSheet()->setCellValue('H' . ($k + 3), $v['engineers_phone']);
            $PHPExcel->getActiveSheet()->setCellValue('I' . ($k + 3), $v['reception_time']);
            $PHPExcel->getActiveSheet()->setCellValue('J' . ($k + 3), $v['assignd_time']);
            $PHPExcel->getActiveSheet()->setCellValue('K' . ($k + 3), $v['assigne_time']);
            $PHPExcel->getActiveSheet()->setCellValue('L' . ($k + 3), $v['contacts']);
            $PHPExcel->getActiveSheet()->setCellValue('M' . ($k + 3), $v['contact_number']);
            $PHPExcel->getActiveSheet()->setCellValue('N' . ($k + 3), $v['username']);
            $PHPExcel->getActiveSheet()->setCellValue('O' . ($k + 3), $v['telphone']);
            $PHPExcel->getActiveSheet()->setCellValue('P' . ($k + 3), ' '.$v['id_card']);
            $PHPExcel->getActiveSheet()->setCellValue('Q' . ($k + 3), $v['contract_no']);
            $PHPExcel->getActiveSheet()->setCellValue('R' . ($k + 3), $v['user_address']);
            $PHPExcel->getActiveSheet()->setCellValue('S' . ($k + 3), $v['equipments_name']);
            //设置居中
            $PHPExcel->getActiveSheet()->getStyle('A1:S' . ($k + 3))->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);

            //垂直居中
            $PHPExcel->getActiveSheet()->getStyle('A' . $k)->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
            $PHPExcel->getActiveSheet()->getStyle('B' . $k)->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
            $PHPExcel->getActiveSheet()->getStyle('C' . $k)->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
            $PHPExcel->getActiveSheet()->getStyle('D' . $k)->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
            $PHPExcel->getActiveSheet()->getStyle('E' . $k)->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
            $PHPExcel->getActiveSheet()->getStyle('F' . $k)->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
            $PHPExcel->getActiveSheet()->getStyle('G' . $k)->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
            $PHPExcel->getActiveSheet()->getStyle('H' . $k)->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
            $PHPExcel->getActiveSheet()->getStyle('I' . $k)->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
            $PHPExcel->getActiveSheet()->getStyle('J' . $k)->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
            $PHPExcel->getActiveSheet()->getStyle('K' . $k)->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
            $PHPExcel->getActiveSheet()->getStyle('L' . $k)->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
            $PHPExcel->getActiveSheet()->getStyle('M' . $k)->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
            $PHPExcel->getActiveSheet()->getStyle('N' . $k)->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
            $PHPExcel->getActiveSheet()->getStyle('O' . $k)->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
            $PHPExcel->getActiveSheet()->getStyle('P' . $k)->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
            $PHPExcel->getActiveSheet()->getStyle('Q' . $k)->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
            $PHPExcel->getActiveSheet()->getStyle('R' . $k)->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
            $PHPExcel->getActiveSheet()->getStyle('S' . $k)->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
        }
        $PHPSheet = $PHPExcel->getActiveSheet();
        //给当前活动sheet设置名称
        $PHPSheet->setTitle("工单");
        //创建生成的格式
        $PHPWriter = \PHPExcel_IOFactory::createWriter($PHPExcel, "Excel5");
        //下载下来的表格名
        ob_end_clean();
        header('content-Type:application/vnd.ms-excel;charset=utf-8');
        header('Content-Disposition: attachment;filename="' . $filename . '"');
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Cache-Control: max-age=0');
        $PHPWriter->save("php://output");
    }

}


